import { CloudOutlined, LogoutOutlined, FolderOutlined, EditOutlined, TableOutlined, FileOutlined, HomeOutlined, FileAddOutlined, DownOutlined } from '@ant-design/icons';
import { Layout, FloatButton, theme, Menu, ConfigProvider, Space, Breadcrumb, Tooltip, Table, message, Button } from 'antd';
import { memo, useState, useRef, useEffect, useCallback } from 'react';
import { useParams, useNavigate, useLocation, Outlet } from 'react-router-dom';

import { useTableColumns } from './fields';
import style from './index.module.less';

import { delContent, delExcel, delFolder, delFile } from '@/apis/delete';
import { previewFile } from '@/apis/file';
import { updateFolder } from '@/apis/folder';
import { useMessage } from '@/hooks/useMessage';
import { FILE_STATUS, formatDate } from '@/utils';
import { clearToken } from '@/utils';

import { useDispatch } from 'react-redux';
import { showMessage } from '@/store/modules/message';
import { clearUserInfo } from '@/store/modules/user';
import { MemoSearch } from '@/components/Search';
import { MemoMenu } from '@/components/Menu';
import { MemoExcel } from '../detail/index.jsx';
import { getExcelContentsByUserId, getExcelListByPage, updateExcel } from '@/apis/excel';

// 是否使用模拟数据（前后端分离开关）
const USE_MOCK_DATA = false;
const { Content, Sider } = Layout;
const ExcelList = () => {
    const {
        token: { colorBgContainer, borderRadiusLG },
    } = theme.useToken();
    const param = useParams()
    const navigate = useNavigate()
    const location = useLocation()
    const [collapsed, setCollapsed] = useState(false);
    const dispatch = useDispatch();
    const { error, contextHolder } = useMessage()
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [modalLoding, setModalLoading] = useState(false)
    const [currentFolder, setCurrentFolder] = useState('')
    const folderName = useRef('')
    const [list, setList] = useState([])
    const [loading, setLoading] = useState(true)
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editModalLoading, setEditModalLoading] = useState(false);
    const [editRecord, setEditRecord] = useState(null);
    const userName = localStorage.getItem('userName');
    const exit = () => {
        dispatch(showMessage({ message: '退出成功', type: 'success' }))
        dispatch(clearUserInfo())
        clearToken()
        navigate('/login')
    }
    const getList = useCallback(async (id = '') => {
        try {
            setLoading(true)
            if (USE_MOCK_DATA) {
                // 使用模拟数据
                setTimeout(() => {
                    // 如果有id参数，模拟只返回该文件夹下的文件
                    setList(id ? [] : []);
                    setLoading(false);
                }, 500);
            } else {
                const res = await getExcelListByPage(
                    { current: 1, pageSize: 10 },
                    { title: '' }
                )
                if (res && res.code === 200 && res.data) {
                    // 取出 excelList
                    const excelList = Array.isArray(res.data.excelList) ? res.data.excelList.map(item => ({
                        id: item.id,
                        title: item.title,
                        owner: item.username,
                        status: 3, // 在线表格
                        updateTime: item.updateTime,
                        createTime: item.createTime,
                    })) : [];
                    setList(excelList);
                } else {
                    setList([]);
                }
                setLoading(false)
            }
        } catch (e) {
            console.error('获取Excel列表失败:', e);
            error({ content: '数据获取失败' })
            setLoading(false)
        }
    }, [error])

    // 搜索处理函数
    const handleSearch = async (value) => {
        if (!value) {
            getList();
            return;
        }
        setLoading(true);
        try {
            const res = await getExcelListByPage(
                { current: 1, pageSize: 10 },
                { title: value.toString() }
            );
            if (res && res.code === 200 && res.data) {
                // 这里要用 res.data.excelList
                const excelList = Array.isArray(res.data.excelList)
                    ? res.data.excelList.map(item => ({
                        id: item.id,
                        title: item.title,
                        owner: item.ownerId, // 这里用 ownerId
                        status: 3,
                        updateTime: item.updateTime,
                        createTime: item.createTime,
                    }))
                    : [];
                setList(excelList);
            } else {
                setList([]);
            }
        } catch (e) {
            setList([]);
        }
        setLoading(false);
    };
    const refreshUrl = () => {
        if (param.id === undefined) navigate(`/home/docList`, { state: { refresh: Date.now() } })
        else navigate(`/home/docList/${param.id}`, { state: { refresh: Date.now() } })
    }
    const handleMenuClick = async (action, record) => {
        if (action === 'edit') {
            setEditRecord({
                ...record,
                title: record.title
            });
            setEditModalOpen(true);
            return;
        }
        if (action === 'details') {
            handleClick(record);
        } else if (action === 'delete') {
            try {
                setLoading(true);
                // 判断是否为在线表格（status === 3）
                if (record.status === 3) {
                    // 调用在线表格删除接口
                    const res = await delExcel(record.id);
                    if (res && res.code === 200) {
                        message.success('删除成功！'); // 删除成功提示
                        getList();
                    } else {
                        message.error('删除失败！');
                        // error({ content: res?.msg || '删除知识库失败' });
                    }
                } else {
                    if (record.status === FILE_STATUS['在线表格']) {
                        setLoading(true);
                        navigate(`/excelList/excelDetail/${record.id}`);
                    }
                    // 删除后刷新列表
                    if (param.id === undefined) getList();
                    else getList(param.id);
                    message.success('删除成功');
                }
            } catch (e) {
                message.error('删除失败');
            }
            setLoading(false);
        } else if (action === 'update') {
            setCurrentFolder(record);
            setIsModalOpen(true);
            folderName.current = record.name;
        } else if (action === 'download') {
            if (USE_MOCK_DATA) {
                // 模拟下载/预览操作
                window.open('https://example.com/preview', '_blank');
            } else {
                preview(record.id);
            }
        }
    };
    const handleEditOk = async (values) => {
        setEditModalLoading(true);
        try {
            // 只用 localStorage 里的 userId 作为 owner
            const owner = localStorage.getItem('userId');
            const params = {
                id: editRecord.id,
                title: values.name,
                url: values.description,
            };
            console.log('编辑知识库参数', params);
            const res = await updateExcel(params);
            console.log('编辑知识库返回', res);
            if (res && res.code === 200) {
                setEditModalOpen(false);
                setEditModalLoading(false);
                setEditRecord(null);
                getList();
            } else {
                setEditModalLoading(false);
                error({ content: res?.msg || '编辑失败' });
            }
        } catch (e) {
            setEditModalLoading(false);
            error({ content: '编辑失败' });
            console.error('编辑知识库失败', e);
        }
    };
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: record => ({
            disabled: record.name === 'Disabled User', // Column configuration not to be checked
            name: record.name,
        }),
    };
    const handleClick = (record) => {
        if (record.status === FILE_STATUS['在线表格']) {
            if (record.status === 3) {
                // 跳转到在线表格详情页，并传递在线表格名称
                navigate(`/excelList/excelDetail/${record.id}`, {
                    state: { knowledgeBaseName: record.name }
                });
            } else {
                navigate(`/home/docList/${record.id}`)
            }
        }
    }
    const handleOk = async () => {
        setModalLoading(true);
        try {
            if (USE_MOCK_DATA) {
                // 模拟更新文件夹名称
                setTimeout(() => {
                    setIsModalOpen(false);
                    setModalLoading(false);
                    // 刷新列表
                    if (param.id === undefined) getList();
                    else getList(param.id);
                }, 500);
            } else {
                // 真实更新操作
                await updateFolder({ name: folderName.current, folderId: currentFolder.id });
                setIsModalOpen(false);
                setModalLoading(false);
                refreshUrl();
            }
        } catch (e) {
            error({ content: '更名失败' });
            setModalLoading(false);
        }
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    useEffect(() => {
        if (param.id === undefined) getList()
        else getList(param.id)
    }, [getList, param.id])
    useEffect(() => {
        if (location.state?.refresh)
            if (param.id === undefined) getList()
            else getList(param.id)
    }, [location.state])
    const { titleColumn, ownerColumn, updateTimeColumn, actionColumn, createTimeColumn } = useTableColumns(handleMenuClick)
    const columns = [titleColumn, updateTimeColumn, createTimeColumn, actionColumn]
    return (
        <Layout style={{
            height: '100vh',
        }}>
            {contextHolder}
            <FloatButton
                icon={<LogoutOutlined />}
                type='primary'
                onClick={exit}
                style={{
                    insetInlineEnd: 38,
                    insetBlockEnd: 100 
                }} />
            <Sider
                width={250}
                breakpoint="lg"
                collapsed={collapsed}
                onCollapse={setCollapsed}
                collapsedWidth={80}
                style={{
                    background: colorBgContainer,
                    overflowY: 'scroll',
                }}
                className={style.sider}
            >
                <div className={style.logo}>{collapsed ? <CloudOutlined style={{
                    fontSize: '25px',
                    color: '#1677ff'
                }} /> : 'CoDoc'}</div>
                <MemoMenu></MemoMenu>
            </Sider>
            <Layout
                style={{
                    padding: '0 24px 0',
                }}
            >
                <Content
                    style={{
                        padding: 24,
                        margin: 0,
                        minHeight: 280,
                        background: colorBgContainer,
                        borderRadius: borderRadiusLG,
                    }}
                >
                    <div style={{
                        fontSize: '24px'
                    }}
                        className={style.breadcrumb}>
                        表格列表
                    </div>
                    <ConfigProvider wave={{ disabled: true }}>
                        <Space size={50} style={{ marginTop: 20 }}>
                            <Button
                                className={style.newExcelBtn}
                                onClick={() => navigate(`/addExcel/main`)}
                            >
                                <FileAddOutlined className={style.firIcon} />
                                新建表格
                            </Button>
                            <MemoSearch onSearch={handleSearch} />
                        </Space>
                        <Table
                            rowSelection={Object.assign({ type: 'checkbox' }, rowSelection)}
                            columns={columns}
                            dataSource={list.map(item => ({ ...item, key: `${item.id}` + `${item.status}`, updateTime: formatDate(item.updateTime) }))}
                            pagination={true}
                            scroll={{ y: 'calc(100vh - 260px)' }}
                            onRow={(record) => ({
                                onClick: () => handleClick(record)
                            })}
                            className={style.fileList}
                        />
                    </ConfigProvider>
                    <div
                        style={{
                            background: colorBgContainer,
                            borderRadius: borderRadiusLG,
                        }}
                        className={style.fileList}
                    >
                        <Outlet></Outlet>
                    </div>
                </Content>
            </Layout>
        </Layout >
    );
}
export const MemoExcelList = memo(ExcelList)